<?php

namespace App\Dao;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use App\Exceptions\SysExceptions;
use App\Model\UsersModel;
use App\Model\MailLogModel;
use App\Services\USDTApiService;
use Illuminate\Support\Facades\DB;

class UsersDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = UsersModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'username'),function ($query)use ($params){
            $query->where('username',$params['username']);
        });

        $query->when(checkIsHasField($params,'spread_id'),function ($query)use ($params){
            $query->where('spread_id',$params['spread_id']);
        });

        return $query->orderByDesc('created_at');
    }


    public static function code($params = [])
    {

        checkForData(['username'],['请输入邮箱'],$params);

        $userQuery = self::builder_query([
            'username'=>$params['username'],
            //'type'=>$params['type'] //获取验证码的类型，如注册，找回密码
        ]);

        //生成随机码
         $generateRandomCode = function($length = 6) {
                $characters = '123456789ABCDEFGHIJKLMNPQRSTUVWXYZ';
                $code = str_shuffle($characters);
                return substr($code, 0, $length);
            };


         $userQuery = self::builder_query([
                'username'=>$params['username']
            ]);
            $mail = new PHPMailer(true); // 创建PHPMailer实例，并启用异常处理
        //注册时
        // if($params['type']==1)
        // {
        //      if($userQuery->exists()){
        //         self::error('账号已存在');
        //     }

        // }else{

        //      if($userQuery->exists()){
        //         self::error('账号不存在');
        //     }
        // }
        $code=$generateRandomCode();
         $from="maoqiaoovuwu125@163.com";//发送者邮箱号   ["to"=>$params['username'],'from'=>$from,'create_at'=>time()]

         Db::table('mail_log')->insert(['to'=>$params['username'],'from'=>$from,'code'=>$code,'create_at'=>time()]);


        //开始执行发送邮件

                // 服务器设置
               // $mail->SMTPDebug = 1; // 启用SMTP调试，输出详细信息
                $mail->isSMTP(); // 设置使用SMTP服务
                $mail->Host = 'smtp.163.com'; // SMTP服务器地址
                $mail->SMTPAuth = true; // 启用SMTP认证
                $mail->Username = $from; // SMTP用户名
                $mail->Password = 'MNp3biVTKvreiQA4'; // SMTP密码
                $mail->SMTPSecure = 'ssl'; // 启用TLS加密，可选值有ssl、tls
                $mail->Port = 465; // SMTP端口，根据服务器配置设置
                // 收件人
                $mail->setFrom($from, $from); // 设置发件人信息

                $mail->addAddress($params['username'], $params['username']); // 添加收件人

                // 邮件内容
                $mail->isHTML(false); // 设置邮件格式为HTML

                $mail->Subject = '验证码'; // 邮件主题

                $mail->Body = '验证码:'.$code."    ,5分钟有效"; // 邮件正文

                // 发送邮件
                if ($mail->send()) {

                   self::error('发送成功');

                } else {

                   self::error('发送失败');

                }



    }

    public static function changepwd($params = [])
    {
        checkForData(['username','password'],['请输入邮箱','请输入新密码','请输入验证码'],$params);

        $userQuery = self::builder_query([
            'username'=>$params['username'],
             //'code'=>$params['code'],
        ]);


         $create_data = [

            'password'=>password_hash($params['password'],PASSWORD_DEFAULT),

        ];

         $query = Db::table('mail_log')->where("to",$params['username'])->orderBy('create_at','desc')->first();


        if($query->code!=$params['code']){
             self::error('验证码错误');
        }
         if($query->create_at+5*60 < time()){
             self::error('验证码已过期');
        }

       // 'code'=>$params['code'],
        //获取发送的验证码  并且验证时间
       if($userQuery->save($create_data)){
           self::error('找回密码失败');
       }




    }


    /**
     * @throws SysExceptions
     */
    public static function register($params = [])
    {
        checkForData(['username','password'],['请输入邮箱','请输入密码','请输入验证码'],$params);
        $userQuery = self::builder_query([
            'username'=>$params['username']
        ]);
        if($userQuery->exists()){
            self::error('账号已存在');
        }
        $create_data = [
            'username'=>$params['username'],
            'code'=>$params['code'],
            'password'=>password_hash($params['password'],PASSWORD_DEFAULT),
            'pay_pass'=>password_hash('123456',PASSWORD_DEFAULT)
        ];

        if(checkIsHasField($params,'spread_id')){
            $create_data['spread_id'] = $params['spread_id'];
        }
          //
          $query = Db::table('mail_log')->where("to",$params['username'])->orderBy('create_at','desc')->first();


         if($query==null||$query->code!=$params['code']){
             self::error('验证码错误');
        }

         if($query->create_at + 5*60 < time()){
             self::error('验证码已过期');
        }


        //
        if($userQuery->create($create_data) === false){
            self::error('注册失败');
        }
    }

    public static function login(array $params)
    {
        checkForData(['username','password'],['请输入手机号','请输入密码'],$params);
        $userQuery = self::builder_query([
            'username'=>$params['username']
        ]);
        if(!$userQuery->exists()){
            self::error('账号不存在');
        }
        $info = $userQuery->first()->toArray();
        if(!password_verify($params['password'],$info['password'])){
            self::error('密码不正确');
        }
        return $info;
    }

    public static function user_info(array $params): array
    {
        $info =  self::builder_query(['user_id'=>$params['user_id']])->first()->toArray();
        $info['level_up'] = self::checkLevelUp($info);
        return $info;
    }

    public static function user_spreads(array $array): array
    {
        $info = self::builder_query(['user_id'=>$array['user_id']])->first();
        $countTuan = 0;
        $spreadTuan = 0;
        $spreadTuanLists = [];
        if($info['spread_ids'] !=  null){
            $spreads = explode(',',$info['spread_ids']);
            $countTuan = (count($spreads)-2) <= 0 ? 0 : count($spreads)-2;
            $spreadTuanLists = self::builder_query([
                'spread_id'=>$array['user_id']
            ])->with('childs')->get();
            $spreadTuan = count($spreadTuanLists);
        }

        return [
            'counts'=>$countTuan,
            'spreads'=>$spreadTuan,
            'lists'=>$spreadTuanLists
        ];
    }

    //用户激活

    /**
     * @throws SysExceptions
     */
    public static function activity(array $params)
    {
        $userInfo = self::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();


        if($userInfo['is_activity'] == 1){
            self::error('用户已激活');
        }
        //激活账户需要扣除150
        if($userInfo['u_price'] < 150){
            self::error('用户金额不足');
        }
        //扣除余额
        DB::beginTransaction();
        try {
            BillsDao::moneyUpdate(-150,$userInfo['user_id'],'用户激活扣除');
            self::builder_query([
                'user_id'=>$userInfo['user_id']
            ])->update([
                'is_activity'=>1
            ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function setPayPass(array $params)
    {
        checkForData(['pay_pass','old_pay_pass'],['请输入支付密码','请输入原支付密码'],$params);
        $userinfo = UsersDao::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($userinfo['pay_pass'] != ''){
            if(!password_verify($params['old_pay_pass'],$userinfo['pay_pass'])){
                self::error('原密码不正确');
            }


            if(password_verify($params['pay_pass'],$userinfo['pay_pass'])){
                self::error('新密码和就密码相同');
            }
        }


        if(self::builder_query([
            'user_id'=>getUserToken()
        ])->update(['pay_pass'=>password_hash($params['pay_pass'],PASSWORD_BCRYPT)]) === false){
            self::error('设置失败');
        }
    }

    public static function setEmail(array $params)
    {
        checkForData(['username','old_username'],['请输入新邮箱','请输入原邮箱'],$params);
        $userinfo = UsersDao::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($params['old_username'] != $userinfo['username']){
            self::error('旧邮箱不正确');
        }
        if($params['username'] == $userinfo['username']){
            self::error('新邮箱和就旧邮箱一致');
        }
        if(self::builder_query([
                'user_id'=>getUserToken()
            ])->update(['username'=>$params['username']]) === false){
            self::error('设置失败');
        }
    }

    private static function checkLevelUp(array $info): bool
    {
        //查看我的所有团队包含自己
        $user_spread_ids = explode(',',$info['spread_ids']);
        $user_spread_ids[] = $info['user_id'];
        if($info['user_level'] == 0){
            //10单
            $count = OrdersDao::builder_query()->whereIn('user_id',$user_spread_ids)->count();
            if($count >= 10){
                return true;
            }
        }else if($info['user_level'] == 10){
            //100单
            $count = OrdersDao::builder_query()->whereIn('user_id',$user_spread_ids)->count();
            if($count >= 100){
                return true;
            }
        }else if($info['user_level'] == 20){
            //1000单 2个上一级
            $count = OrdersDao::builder_query()->whereIn('user_id',$user_spread_ids)->count();
            if($count >= 1000){
                return true;
            }
        }else if($info['user_level'] == 30){
            //10000单 2个上一级
            $count = OrdersDao::builder_query()->whereIn('user_id',$user_spread_ids)->count();
            if($count >= 10000){
                return true;
            }
        }else if($info['user_level'] == 40){
            //100000单 3个上一级
            $count = OrdersDao::builder_query()->whereIn('user_id',$user_spread_ids)->count();
            if($count >= 100000){
                return true;
            }
        }
        return false;
    }

    /**
     * @throws SysExceptions
     */
    public static function levelUpU($params = []){
        checkForData(['user_id'],['请选择用户'],$params);
        $user_id = $params['user_id'];
        $info = self::user_info([
            'user_id'=>$user_id
        ]);
        if(!$info['level_up']){
            self::error('升级失败');
        }
        if(self::builder_query([
            'user_id'=>$user_id
        ])->update([
            'user_level'=>$info['user_level']+10
        ]) === false){
            self::error('升级失败');
        }
    }


    /**
     * @throws SysExceptions
     */
    public static function setPayPassUser($params = [])
    {
        checkForData(['user_id','pay_pass'],['请选择用户','请输入支付密码'],$params);
        if(self::builder_query([
                'user_id'=>$params['user_id']
            ])->update(['pay_pass'=>password_hash($params['pay_pass'],PASSWORD_BCRYPT)]) === false){
            self::error('设置失败');
        }
    }

    public static function pageUsers(array $all)
    {
        return self::builder_query($all)->paginate();
    }

    /**
     * @throws SysExceptions
     */
    public static function recharge(array $params): array
    {
        $arr = ['money','address','rdatasource'];
        $tip = ['请输入重置数量','请输入付款地址','请选择充值的链'];
        checkForData($arr,$tip,$params);
        $order_code = makeOrderNo();
        $params['order_sn'] = $order_code;
        $params['pay_usdt'] = $params['money'];

        if(RechargeDao::builder_query()->create($params) === false){
            self::error('下单失败');
        }
        return $params;
    }

    /**
     * @throws SysExceptions
     */
    public static function withdrawal(array $params)
    {
        checkForData(['pay_pass','address','pay_usdt'],['请输入支付密码','请输入提取地址','请输入提取额度'],$params);
        $userInfo = self::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if(!password_verify($params['pay_pass'],$userInfo['pay_pass'])){
            self::error('支付密码不正确');
        }
        if($userInfo['u_price'] < $params['pay_usdt']){
            self::error('用户金额不足');
        }
        if($params['pay_usdt'] < 100){
            self::error('最少提现100');
        }
        DB::beginTransaction();
        //创建到表格
        try {
            WithdrawalDao::builder_query()->create($params);
            BillsDao::moneyUpdate(-($params['pay_usdt']),$params['user_id'],'提现扣款');
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function rechargeAdmin(array $all)
    {
        $arr = ['money'];
        $tip = ['请输入重置数量'];
        checkForData($arr,$tip,$all);
        DB::beginTransaction();
        try {
            BillsDao::moneyUpdate($all['money'],$all['user_id'],'后台充值金额');
            DB::commit();
        }catch ( \Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function setPass(array $params)
    {
        checkForData(['password','old_password'],['请输入密码','请输入原密码'],$params);
        $userinfo = UsersDao::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if(!password_verify($params['old_password'],$userinfo['password'])){
            self::error('原密码不正确');
        }


        if(self::builder_query([
                'user_id'=>getUserToken()
            ])->update(['password'=>password_hash($params['password'],PASSWORD_BCRYPT)]) === false){
            self::error('设置失败');
        }
    }

    public static function editInfo(array $all)
    {
        $update = [
            'user_level'=>$all['user_level']
        ];
        if(checkIsHasField($all,'password')){
            $update['password'] = password_hash($all['password'],PASSWORD_DEFAULT);
        }
        $result = self::builder_query(['user_id'=>$all['user_id']])->update($update);
        if($result === false){
            self::error('设置失败');
        }
    }
}
